#include "synchronizator.h"
#include <string>
#include <stack>

using namespace std;
namespace fs = boost::filesystem;

void Synchronizator::synchronize(string from, string to, Compare *A) {
	stack<fs::path> parents;
	if(from[from.length()-1]=='/') {
		from = from.erase(from.length()-1, 1);
	}
	if(to[to.length()-1]=='/') {
		to = to.erase(to.length()-1, 1);
	}
	while(!A->getComparedFiles().empty()) {
		fs::path file(from + A->getComparedFiles().back());
		fs::path duplicate(to + A->getComparedFiles().back());
		A->popComparedFiles();
		fs::path tmp = duplicate;
		while(tmp.parent_path().string() != "") {
			parents.push(tmp.parent_path());
			tmp=tmp.parent_path();
		}
		while(!parents.empty()) {
			if(!is_directory(parents.top())) {
				fs::create_directory(parents.top());
			}
			parents.pop();
		}
		//while(tmp.parent_path().string() != "") {
		//	if(!is_directory(tmp.parent_path())) {
		//		fs::create_directory(duplicate.parent_path());
		//	}
		//	tmp=tmp.parent_path();
		//}

		fs::copy_file(file, duplicate, fs::copy_option::overwrite_if_exists);
	}
}
